package www.bwsensing.com.common.netty.initializer;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import www.bwsensing.com.common.constant.NettyConstants;
import www.bwsensing.com.common.netty.decoder.NettyServerDecoder;
import www.bwsensing.com.common.netty.handler.NettyTcpServerHandler;

import java.util.concurrent.TimeUnit;


/**
 * @author macos-zyj
 */
@Slf4j
@Data
public class NettyTcpInitializer extends ChannelInitializer<SocketChannel> {

    private NettyTcpServerHandler nettyServerHandler;

    public NettyTcpInitializer(NettyTcpServerHandler nettyServerHandler) {
        this.nettyServerHandler = nettyServerHandler;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(new IdleStateHandler(
                NettyConstants.SERVER_READ_IDEL_TIME_OUT,
                NettyConstants.SERVER_WRITE_IDEL_TIME_OUT,
                NettyConstants.SERVER_ALL_IDEL_TIME_OUT,
                TimeUnit.SECONDS))
        .addLast("aggregator", new HttpObjectAggregator(512 * 1024))
        .addLast(new StringEncoder())
        .addLast(new ByteArrayEncoder())
        .addLast("decoder",new NettyServerDecoder())
        .addLast("nettyServerHandler", nettyServerHandler);
    }

}
